package models

import (
	"fmt"
	beego "github.com/beego/beego/v2/adapter"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mssql"
)

type mssqlConnection struct {
	User     string
	Password string
	Host     string
	Port     int64
	Dbname   string
	DataBase *gorm.DB
}

func (o *mssqlConnection) connect() error {
	user := beego.AppConfig.String("mssql::user")
	password := beego.AppConfig.String("mssql::password")
	host := beego.AppConfig.String("mssql::host")
	port, _ := beego.AppConfig.Int64("mssql::port")
	dbname := beego.AppConfig.String("mssql::dbname")
	connectionString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s",
		host, user, password, port, dbname)
	db, err := gorm.Open("mssql", connectionString)
	if err != nil {
		return err
	}
	db.LogMode(true)
	db.CommonDB()
	o.DataBase = db
	return nil
}

type UserInfo struct {
	Id            string `gorm:"column:VAA01"`
	PatientIdcard string `gorm:"column:VAA02"`
	Name          string `gorm:"column:VAA05"`
	Sex           string `gorm:"column:ABW01"`
	Idcard        string `gorm:"column:VAA15"`
	Mobile        string `gorm:"column:VAA35"`
	Birthday      string `gorm:"column:VAA12"`
}

//TableName 表名
func (m *UserInfo) TableName() string {
	return "VAA1"
}

//GetList 取所有数据列表
func (m *UserInfo) GetOne(idcard string) (datas []*UserInfo, err error) {
	mssql := new(mssqlConnection)
	err = mssql.connect()
	if  err != nil {
		return nil, err
	}
	db := mssql.DataBase
	defer db.Close()
	err = db.Select("TOP 1 *").Where("VAA02 = ?", idcard).Order("VAA01 DESC").Find(&datas).Error
	return
}
